
type CampusData = {
    [campus: string]: {
      weight: number,
      restaurants: {
        [restaurant: string]: {
          weight: number,
          floors: {
            [floor: string]: {
              weight: number,
              stalls: {
                [stall: string]: {
                  weight: number,
                  dishes: { name: string, weight: number }[]
                }
              }
            }
          }
        }
      }
    }
  };
  
  interface Announcement {
    id: number;
    title: string;
    content: string;
    created_at: string;
  }
  
  interface Advertisement {
    id: number;
    title: string;
    image_url: string;
    created_at: string;
  }
  
  interface AnnouncementData {
    announcements: Announcement[]
  }
  
  interface AdvertisementData {
    advertisements: Advertisement[]
  }
  
  Page({
    data: {
      campuses: ['随便'],
      restaurants: ['随便'],
      floors: ['随便'],
      stalls: ['随便'],
      dishes: ['随便'],
      campusData: {} as CampusData,
      selectedCampus: '随便',
      selectedRestaurant: '随便',
      selectedFloor: '随便',
      selectedStall: '随便',
      advertisement: {} as Advertisement,
      announcement: {} as Announcement,
      result: '',
      imageUrl: '',
      price: 0,
      selectedRice: false,
      selectedNoodles: false,
      selectedSnack: false
    },
  
    onLoad: function() {
      this.fetchData();
    },
  
    fetchData: function() {
      const that = this;
      wx.request({
        url: 'https://food.api.lttac.cn/api/getData',
        method: 'GET',
        success: function(res) {
          if (typeof res.data === 'object' && res.data !== null && 'campuses' in res.data) {
            const campusData: CampusData = {};
            const campuses = res.data.campuses.map((campus: any) => {
              campusData[campus.name] = {
                weight: campus.weight,
                restaurants: {}
              };
              campus.restaurants.forEach((restaurant: any) => {
                campusData[campus.name].restaurants[restaurant.name] = {
                  weight: restaurant.weight,
                  floors: {}
                };
                restaurant.floors.forEach((floor: any) => {
                  campusData[campus.name].restaurants[restaurant.name].floors[floor.name] = {
                    weight: floor.weight,
                    stalls: {}
                  };
                  floor.stalls.forEach((stall: any) => {
                    campusData[campus.name].restaurants[restaurant.name].floors[floor.name].stalls[stall.name] = {
                      weight: stall.weight,
                      dishes: stall.dishes.map((dish: any) => ({ name: dish.name, weight: dish.weight }))
                    };
                  });
                });
              });
              return campus.name;
            });
            that.setData({ campuses: ['随便'].concat(campuses), campusData: campusData });
          } else {
            console.error('Invalid response format', res.data);
          }
        },
        fail: function(error) {
          console.error('Request failed', error);
        }
      });
  
      wx.request({
        url: 'https://food.api.lttac.cn/api/announcement',
        method: 'GET',
        success: function(res) {
          if (typeof res.data === 'object' && res.data !== null && 'announcements' in res.data) {
            const announcements = (res.data as { announcements: Announcement[] }).announcements;
            if (announcements.length > 0) {
              that.setData({ announcement: announcements[0] });
            }
          } else {
            console.error('公告数据格式错误或无数据', res.data);
          }
        },
        fail: function(error) {
          console.error('公告请求失败', error);
        }
      });
  
      wx.request({
        url: 'https://food.api.lttac.cn/api/advertisement',
        method: 'GET',
        success: function(res) {
          if (typeof res.data === 'object' && res.data !== null && 'advertisements' in res.data) {
            const advertisements = (res.data as { advertisements: Advertisement[] }).advertisements;
            if (advertisements.length > 0) {
              that.setData({ advertisement: advertisements[0] });
            }
          } else {
            console.error('广告数据格式错误或无数据', res.data);
          }
        },
        fail: function(error) {
          console.error('广告请求失败', error);
        }
      });
    },
  
    getWeightedRandomItem: function(items: { name: string, weight: number }[]) {
        const totalWeight = items.reduce((sum, item) => sum + item.weight, 0);
        let randomValue = Math.random() * totalWeight;
        for (let item of items) {
            if (randomValue < item.weight) {
                return item;
            }
            randomValue -= item.weight;
        }
        return items[items.length - 1]; // 默认返回最后一项，作为保障
    },
    startLottery: function() {
      let { selectedCampus, selectedRestaurant, selectedFloor, selectedStall, campuses, campusData } = this.data;
      
      let campus, restaurant, floor, stall, dish;
      do {
        campus = selectedCampus === '随便' ? this.getWeightedRandomItem(campuses.filter(c => c !== '随便').map(name => ({ name, weight: 1 })))!.name : selectedCampus;
        restaurant = selectedRestaurant === '随便' ? this.getWeightedRandomItem(Object.entries(campusData[campus].restaurants).map(([name, data]) => ({ name, weight: data.weight })))!.name : selectedRestaurant;
        floor = selectedFloor === '随便' ? this.getWeightedRandomItem(Object.entries(campusData[campus].restaurants[restaurant].floors).map(([name, data]) => ({ name, weight: data.weight })))!.name : selectedFloor;
        stall = selectedStall === '随便' ? this.getWeightedRandomItem(Object.entries(campusData[campus].restaurants[restaurant].floors[floor].stalls).map(([name, data]) => ({ name, weight: data.weight })))!.name : selectedStall;
        dish = this.getWeightedRandomItem(campusData[campus].restaurants[restaurant].floors[floor].stalls[stall].dishes)!.name;
      } while (!dish);
  
      console.log('Selected dish:', dish);
      this.setData({ result: `${campus} ${restaurant} ${floor} ${stall} - ${dish}`, imageUrl: '', price: 0 });
      this.fetchDishDetails(dish);
    },
  
    fetchDishDetails: function(dish: string) {
      const that = this;
      console.log('Fetching details for dish:', dish);
      wx.request({
        url: `https://food.api.lttac.cn/api/getDishDetails?dish=${dish}`,
        method: 'GET',
        success: function(res) {
          if (res.data && typeof res.data === 'object' && 'image' in res.data && 'price' in res.data) {
            that.setData({ imageUrl: `data:image/png;base64,${res.data.image}`, price: res.data.price });
          } else {
            console.error('Invalid dish details', res.data);
          }
        },
        fail: function(error) {
          console.error('Request failed', error);
        }
      });
    },
    navigateToAddData: function() {
      wx.navigateTo({
        url: '/pages/adddata/adddata' // 确保路径正确
      });
    }
  });
  